/*
 * @Description:
 * @Author: william
 * @Date: 2025-08-06 14:15:15
 * @LastEditors: william
 * @LastEditTime: 2025-08-12 14:45:19
 */
// 连接EventSource
class EventSourceClient {
  url
  maxReconnectInterval = 30000 // 最大重连间隔（毫秒）-30秒
  reconnectInterval = 10000 // 重连间隔增长因子-初始10秒
  maxRetries = 3 // 最大重连次数
  retryCount = 0 // 当前重连次数
  eventSource = null
  eventListeners = new Map() // 存储事件监听器

  constructor(url) {
    this.url = url
    this.connect()
  }

  connect() {
    this.eventSource = new EventSource(this.url, {
      withCredentials: true // 携带凭据
    })
    this.onerror()
    this.onopen()
    this.onmessage()
  }

  reconnect() {
    // if (this.retryCount < this.maxRetries) {
    //   console.log(
    //     `第${this.retryCount + 1}次重连,间隔${this.reconnectInterval}ms`
    //   )
    //   setTimeout(() => this.connect(), this.reconnectInterval)
    //   this.retryCount++
    //   this.reconnectInterval = Math.min(
    //     this.reconnectInterval * 2,
    //     this.maxReconnectInterval
    //   )
    // }
    setTimeout(() => this.connect(), this.reconnectInterval)
  }

  onmessage(cb) {
    this.eventSource.onmessage = e => {
      console.log('onmessage', e)
      // 处理消息逻辑...
      cb(e)
    }
  }

  /**
   * 添加事件监听
   * @param {string} eventName - 事件名称
   * @param {function} callback - 回调函数
   */
  on(eventName, callback) {
    // console.log('添加事件监听', this.eventListeners.has(eventName))
    if (!this.eventListeners.has(eventName)) {
      // console.log('添加事件监听', eventName)
      this.eventListeners.set(eventName, new Set())

      // 如果是自定义事件且连接已建立，添加原生监听
      if (
        this.eventSource &&
        eventName !== 'message' &&
        eventName !== 'open' &&
        eventName !== 'error'
      ) {
        this.eventSource.addEventListener(eventName, callback)
      }
    }

    this.eventListeners.get(eventName).add(callback)
    // console.log('this.eventListeners', this.eventListeners)
  }

  /**
   * 移除事件监听
   * @param {string} eventName - 事件名称
   * @param {function} callback - 回调函数
   */
  off(eventName, callback) {
    // console.log('移除事件监听', this.eventListeners.has(eventName))
    if (this.eventListeners.has(eventName)) {
      // console.log('移除事件监听', eventName)
      const listeners = this.eventListeners.get(eventName)
      listeners.delete(callback)

      if (listeners.size === 0) {
        this.eventListeners.delete(eventName)
        // 可以考虑移除原生事件监听
        this.eventSource.removeEventListener(eventName, callback)
      }
    }
    // console.log('this.eventListeners', this.eventListeners)
  }

  /**
   * 触发事件
   * @private
   */
  // emit(eventName, ...args) {
  //   if (this.eventListeners.has(eventName)) {
  //     this.eventListeners.get(eventName).forEach(callback => {
  //       try {
  //         callback(...args)
  //       } catch (err) {
  //         console.error(`事件${eventName}处理错误:`, err)
  //       }
  //     })
  //   }
  // }

  onerror() {
    this.eventSource.onerror = e => {
      console.error('EventSource 错误:', e)
      if (e.target.readyState === EventSource.CLOSED) {
        // 连接已关闭，手动重连
        this.close()
        this.reconnect()
      }
    }
  }

  onopen() {
    this.eventSource.onopen = e => {
      console.log('连接已建立:', e)
      this.reconnectInterval = 1000 // 重置重连延迟
      this.retryCount = 0
    }
  }

  close() {
    this.eventSource.close()
    console.log('SSE连接已关闭')
  }
}

// 示例
// new EventSourceClient('/sse').onmessage(data => {
//   console.log('data', data)
// })

export default EventSourceClient
